﻿/*
 * RegExpress
 * 
 * Copyright (c) 2010, Daniel McGaughran
 * 
 * Licensed under the Apache Licence, Version 2.0 (the "Licence");
 * you may not use this file except in compliance with the Licence.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 * 
 */

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;


namespace XrControls.Util
{
    public class TemplateNavigator : DependencyObject
    {
        public static readonly DependencyProperty EnableProperty;
        private static NavigationService _nav;


        static TemplateNavigator()
        {
            _nav = null;

            EnableProperty = DependencyProperty.RegisterAttached("Enable", typeof(bool), typeof(TemplateNavigator),
                new FrameworkPropertyMetadata(false, HandleNavigatorEnabled));
        }


		public static Action<FrameworkElement> SetDataContext { get; set; }



        public static bool GetEnable(FrameworkElement target)
        {
            return (bool)target.GetValue(EnableProperty);
        }

        public static void SetEnable(FrameworkElement target, bool value)
        {
            target.SetValue(EnableProperty, value);
        }



        static void HandleNavigatorEnabled(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            if (target is Page)
            {
                Page castTarget = (Page)target;

                if((bool)e.NewValue)
                    castTarget.Loaded += InitialiseDataContextForPage;
                else
                    castTarget.Loaded -= InitialiseDataContextForPage;
            }
        }



        static void InitialiseDataContextForPage(object sender, RoutedEventArgs e)
        {
        	Page sourcePage = (Page)(e.Source);

            if(_nav == null)
                _nav = NavigationService.GetNavigationService(sourcePage);

			if(SetDataContext != null)
				SetDataContext(sourcePage);
        }


    }
}
